var RedisStore = require("connect-redis")(require("express-session"));
var CookieParser = require("cookie-parser");
var Cookie = require("cookie");

var KOC = require("koc.common.utils");

var Config = require("../config");
var StateModel = require("./statemodel");

var StateData = module.exports = {
    ////////////////////////////////////
    //初始化
    ////////////////////////////////////
    Init: function (callback) {
        var _RedisStore = new RedisStore(Config.Redis.Session);
        return function (socket, next) {
            _RedisStore.get(StateData.SessionID(socket), function (err, session) {
                if (!err) {
                    // socket.Session = session;
                    socket.StateData = session && session.Data ? session.Data : StateModel.New();
                    socket.StateData.NickName = socket.StateData.NickName || "游客 " + KOC.Moment().format("HHmmssSSS");
                    socket.UserID = socket.StateData.IsLogin ? socket.StateData.User_ID : socket.id.replace(/#/g, "_").replace(/\//g, "_");
                    socket.IsMobile = false;
                }
                callback(err, session, socket, next);
            });
        }
    },
    ////////////////////////////////////
    //初始化(移动端)
    ////////////////////////////////////
    InitMobile: function (socket, data) {
        socket.StateData = data || StateModel.New();
        socket.StateData.NickName = socket.StateData.NickName || "游客 " + KOC.Moment().format("HHmmssSSS");
        socket.StateData.IsLogin = data ? true : false;
        socket.UserID = socket.StateData.IsLogin ? socket.StateData.User_ID : socket.id.replace(/#/g, "_").replace(/\//g, "_");
        socket.IsMobile = true;
    },
    ////////////////////////////////////
    //取得SessionID
    ////////////////////////////////////
    SessionID: function (socket) {
        if (!socket.request.headers.cookie) {
            return "";
        }
        return CookieParser.signedCookie(Cookie.parse(socket.request.headers.cookie)["connect.sid"] || "", Config.Common.Session_Ssecret);
    },
    ////////////////////////////////////
    //取得用户状态
    ////////////////////////////////////
    Get: function (socket, id) {
        return socket.sockets[id] ? socket.sockets[id].StateData : StateModel.New();
    }
};